// pages/vote_detail/index.js

// 本地存储工具函数
const VOTE_STORAGE_KEY = 'vote_records'

function getVoteRecord(voteId) {
  try {
    const records = wx.getStorageSync(VOTE_STORAGE_KEY) || {}
    return records[voteId] || null
  } catch (e) {
    console.error('读取投票记录失败:', e)
    return null
  }
}

function setVoteRecord(voteId, optionIndex) {
  try {
    const records = wx.getStorageSync(VOTE_STORAGE_KEY) || {}
    records[voteId] = {
      votedOptionIndex: optionIndex,
      votedAt: Date.now()
    }
    wx.setStorageSync(VOTE_STORAGE_KEY, records)
  } catch (e) {
    console.error('存储投票记录失败:', e)
  }
}

function clearVoteRecord(voteId) {
  try {
    const records = wx.getStorageSync(VOTE_STORAGE_KEY) || {}
    delete records[voteId]
    wx.setStorageSync(VOTE_STORAGE_KEY, records)
  } catch (e) {
    console.error('清除投票记录失败:', e)
  }
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    voteId: '',
    voteInfo: null,
    selectedOption: -1,
    hasVoted: false,
    loading: true,
    submitting: false,
    showResult: true, // 排行榜模式默认显示结果
    sortedOptions: [], // 排序后的选项
    userVotedIndex: -1, // 用户投票的选项索引
    navBarHeight: 0, // 导航栏总高度 = 状态栏高度 + 导航栏高度
    contentTop: 0, // 内容区域top位置
    bottomSafeArea: 0 // 底部安全区域高度
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const voteId = options.voteId
    if (!voteId) {
      wx.showToast({
        title: '投票ID无效',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }

    this.setData({ voteId })
    this.initNavHeight()
    this.loadVoteDetail()
  },

  /**
   * 初始化导航栏高度和底部安全区域
   */
  initNavHeight() {
    try {
      const systemInfo = wx.getSystemInfoSync()
      const statusBarHeight = systemInfo.statusBarHeight
      const navBarHeight = statusBarHeight + 44 // 44是导航栏内容高度
      const bottomSafeArea = systemInfo.safeArea ? systemInfo.screenHeight - systemInfo.safeArea.bottom : 0
      
      this.setData({
        navBarHeight,
        contentTop: navBarHeight,
        bottomSafeArea
      })
    } catch (error) {
      this.setData({
        navBarHeight: 64,
        contentTop: 64,
        bottomSafeArea: 0
      })
    }
  },

  /**
   * 加载投票详情
   */
  async loadVoteDetail() {
    try {
      this.setData({ loading: true })
      
      const result = await wx.cloud.callFunction({
        name: 'getVoteDetail',
        data: { voteId: this.data.voteId }
      })

      if (result.result.success) {
        const voteInfo = {
          ...result.result.data,
          isEnded: result.result.data.endTime ? new Date() > new Date(result.result.data.endTime) : false,
          // 处理云存储背景图片URL
          backgroundImage: this.processCloudImageUrl(result.result.data.backgroundImage),
          // 预格式化时间
          formattedEndTime: this.formatEndTime(result.result.data.endTime)
        }
        const hasVoted = result.result.hasVoted || false
        
        // 获取用户投票的选项索引
        let userVotedIndex = -1
        if (hasVoted && result.result.userVoteRecord) {
          userVotedIndex = result.result.userVoteRecord.option
        }

        // 按票数排序选项
        const sortedOptions = voteInfo.options
          .map((option, index) => ({
            ...option,
            originalIndex: index
          }))
          .sort((a, b) => (b.votes || 0) - (a.votes || 0))

        // 检查本地存储的投票记录
        let selectedOption = -1
        const localVote = getVoteRecord(this.data.voteId)
        if (localVote) {
          selectedOption = localVote.votedOptionIndex
          // 如果本地记录与云端不一致，以云端为准
          if (hasVoted && userVotedIndex !== -1 && userVotedIndex !== selectedOption) {
            selectedOption = userVotedIndex
            // 更新本地记录
            setVoteRecord(this.data.voteId, userVotedIndex)
          } else if (!hasVoted) {
            // 云端显示未投票，清除本地记录
            clearVoteRecord(this.data.voteId)
            selectedOption = -1
          }
        } else if (hasVoted && userVotedIndex !== -1) {
          // 云端有记录但本地没有，同步到本地
          selectedOption = userVotedIndex
          setVoteRecord(this.data.voteId, userVotedIndex)
        }

        this.setData({
          voteInfo,
          hasVoted,
          sortedOptions,
          userVotedIndex,
          selectedOption,
          showResult: true, // 排行榜模式始终显示结果
          loading: false
        })

        // 设置页面标题
        wx.setNavigationBarTitle({
          title: voteInfo.title || '投票详情'
        })
      } else {
        console.error('获取投票详情失败:', result.result.message)
        wx.showToast({
          title: '获取投票详情失败',
          icon: 'none'
        })
        this.setData({ loading: false })
      }
    } catch (error) {
      console.error('加载投票详情出错:', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },

  /**
   * 点击投票选项
   */
  onVoteForOption(e) {
    if (this.data.hasVoted || this.data.voteInfo.isEnded) {
      return
    }

    const optionIndex = parseInt(e.currentTarget.dataset.index)
    this.setData({
      selectedOption: optionIndex
    })
  },

  /**
   * 提交投票
   */
  async onSubmitVote() {
    if (this.data.submitting) return
    
    if (this.data.selectedOption === -1) {
      wx.showToast({
        title: '请选择一个选项',
        icon: 'none'
      })
      return
    }

    if (this.data.hasVoted) {
      wx.showToast({
        title: '您已经投过票了',
        icon: 'none'
      })
      return
    }

    if (this.data.voteInfo.isEnded) {
      wx.showToast({
        title: '投票已结束',
        icon: 'none'
      })
      return
    }

    try {
      this.setData({ submitting: true })

      const result = await wx.cloud.callFunction({
        name: 'submitVote',
        data: {
          voteId: this.data.voteId,
          optionIndex: this.data.selectedOption
        }
      })

      if (result.result.success) {
        wx.showToast({
          title: '投票成功',
          icon: 'success'
        })

        // 存储投票记录到本地
        setVoteRecord(this.data.voteId, this.data.selectedOption)

        // 重新加载数据显示结果
        this.setData({
          hasVoted: true,
          userVotedIndex: this.data.selectedOption,
          showResult: true
        })
        
        // 延迟刷新数据
        setTimeout(() => {
          this.loadVoteDetail()
        }, 1000)
      } else {
        wx.showToast({
          title: result.result.message || '投票失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('提交投票出错:', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ submitting: false })
    }
  },

  /**
   * 查看活动详情
   */
  onViewActivityDetail() {
    if (!this.data.voteInfo || !this.data.voteInfo._activityId) {
      wx.showToast({
        title: '活动信息不存在',
        icon: 'none'
      })
      return
    }

    wx.navigateTo({
      url: `/pages/activity_detail/index?id=${this.data.voteInfo._activityId}`
    })
  },


  /**
   * 计算百分比
   */
  calculatePercentage(votes, totalVotes) {
    if (!totalVotes || totalVotes === 0) return '0'
    return ((votes / totalVotes) * 100).toFixed(1)
  },

  /**
   * 处理云存储图片URL
   */
  processCloudImageUrl(imageUrl) {
    if (!imageUrl) return ''
    
    // 如果已经是完整的URL，直接返回
    if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
      return imageUrl
    }
    
    // 如果是云存储路径，确保格式正确
    if (imageUrl.startsWith('cloud://')) {
      return imageUrl
    }
    
    // 处理fileID格式的云存储路径
    if (imageUrl.startsWith('cloudbase-1g29vs061fa4f865')) {
      return `cloud://${imageUrl}`
    }
    
    return imageUrl
  },

  /**
   * 格式化时间
   */
  formatEndTime(endTime) {
    if (!endTime) return ''
    const date = new Date(endTime)
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
  },

  /**
   * 导航栏返回按钮点击
   */
  onNavBack() {
    wx.navigateBack()
  },

  /**
   * 分享功能
   */
  onShareAppMessage() {
    return {
      title: this.data.voteInfo?.title || '快来参与投票吧',
      path: `/pages/vote_detail/index?voteId=${this.data.voteId}`,
      imageUrl: this.data.voteInfo?.backgroundImage
    }
  }
})